package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestCustomUrl {
	public static String post(String user,String password,String link)
	{
		String str = "-1";
		try {
			URL url = new URL(link);
			String title = "Test submit content from hatforent";
		    String description = "Test submit content from <a href='http://hatforrent.com'>hatforent</a>";
			
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	        writer.write("post[title]=" + title);
	        writer.write("&post[content]="+description);
	        writer.write("&post[tag]=" + "");
	        writer.write("&post[user]=" + user);
	        writer.write("&post[password]=" + password);
	        writer.close();
	        
	        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        	 String content = "";
            	 char[] buf = new char[102102];
         		 int numRead=0;
                 while((numRead=reader.read(buf)) != -1){
                     String readData = String.valueOf(buf, 0, numRead);
                     content += readData;
                     buf = new char[102102];
                 }
                 reader.close();
                 str = content.replaceAll("\\{\"id\":", "").replaceAll("\\}", "");
	        } else {
	            // Server returned HTTP error code.
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	public static void main(String[] args) {
		post("user","","http://picmul.herokuapp.com/posts");
	}
}
